package org.test.myTree.AbstractTree;

import java.io.Serializable;
import java.util.List;


import org.apache.log4j.Logger;
import org.test.dao.ITbDepartmentDAO;
import org.test.myTree.TbDepartment;


/**
 * 应急部门通讯录树,保存在服务器内存 单例模式——线程安全
 * 
 * @author 张颢铧
 * 
 */

public class EmergencyTree extends AbstractTree implements Serializable {
	private static Logger logger = Logger.getLogger(EmergencyTree.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = -3149071186653147609L;
	private volatile static EmergencyTree instance = null;
	private static Object lock = new Object();
	private EmergencyTree() {

	}

	public static EmergencyTree getInstance(ITbDepartmentDAO deptDao) {
		if (instance == null) {
			synchronized (lock) {
				if (instance == null) {
					instance = new EmergencyTree();
					logger.info("EmergencyTree----------reloading");
					instance.reloadEmergencyDept(deptDao);
				}
			}
		}
		return instance;
	}
	
	public static void updateEmergencyTree(ITbDepartmentDAO deptDao) {
			synchronized (lock) {
				if (instance == null) {
					instance = new EmergencyTree();
					logger.info("EmergencyTree----------reloading");
					instance.reloadEmergencyDept(deptDao);
				}
			}
	}

	@Override
	protected TreeNode transform(Object info) {
		// 将Object对象转换为树的结点
		TbDepartment dept = (TbDepartment) info;
		TreeNode node = new TreeNode();
		node.setNodeId(dept.getTbDepartmentId());
		node.setName(dept.getTbDepartmentName());
		if (dept.getParentDepartment() != null) {	//父节点,把node的parentid放进去
			node.setParentId(dept.getParentDepartment().getTbDepartmentId());
		}
		node.setBindData(dept);
		return node;
	}

	/**
	 * 找到nodes，放到reload去
	 * @param deptDao
	 */
	public void reloadEmergencyDept(ITbDepartmentDAO deptDao) {
		List objects;
		try {
			objects = deptDao.findAll();//得到 list<dept>
			super.reload(objects);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
